package com.wangyadong.hobby.schedule.jobtask.threadqueue;

import java.util.LinkedList;
import java.util.stream.IntStream;

/**
 * @ClassName EventQueue
 * @Description TODO
 * @Authpr Antonio
 * @Data 2018-07-11 12:10
 */
public class EventQueue {

    static class Event

    {
    }

    private LinkedList linkedList = new LinkedList();

    private final int Metux = 10;
    private final int max;

    public EventQueue() {
        max = 10;
    }

    public EventQueue(int max) {
        this.max = max;
    }

    public void offer(Event event) throws InterruptedException {
        synchronized (linkedList) {
            if (linkedList.size() >= max) {
                linkedList.wait();
                System.out.println("task is full");
            }
            System.out.println("new task is submiit");
            linkedList.addFirst(event);
            linkedList.notify();
        }
    }

    public Event take() throws InterruptedException {
        synchronized (linkedList) {
            if (linkedList.isEmpty()) {
                System.out.println("queue task is enpyt");
                linkedList.wait();
            }
            Event o = (Event) linkedList.removeFirst();
            System.out.println("this event " + o + "is handle");
            linkedList.notify();
            return o;
        }
    }

    public static void main(String[] args) {

        EventQueue eventQueue = new EventQueue();
        IntStream.range(0, 5).forEach(r -> {
            new Thread(() -> {
                while (true) {
                    try {
                        eventQueue.offer(new Event());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "生产者").start();


        });

        IntStream.range(0, 5).forEach(r -> {
            new Thread(() -> {
                while (true) {
                    try {
                        eventQueue.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "消费者").start();
        });

    }

}
